package com.bawei.yuekao.fragment;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.bawei.yuekao.Mode;
import com.bawei.yuekao.MusicService;
import com.bawei.yuekao.R;
import com.bawei.yuekao.adapter.NetSongAdapter;
import com.bawei.yuekao.entity.NetSong;
import com.bawei.yuekao.utils.HttpUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * 网络音乐
 */
public class NetMusicFragment extends Fragment {
    private View view;
    private ListView lv;
    private ImageView iv;
    private TextView tvName;
    private TextView tvSinger;
    private ImageView ivPre;
    private ImageView ivStartOrPause;
    private ImageView ivNext;
    private ImageView ivMode;
    private NetSongAdapter mNetSongAdapter;
    private List<NetSong.DataBean> mList = new ArrayList<>();
    //广播接受者
    private MusicRecevier mMusicRecevier;

    //服务链接
    private MusicService.MusicBinder mMusicBinder;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMusicBinder = (MusicService.MusicBinder) service;
            Toast.makeText(getContext(),"绑定成功",Toast.LENGTH_LONG).show();
            //设置数据
            mMusicBinder.setSongs(mList);
            //默认播放歌曲
            mMusicBinder.play();


        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_net_music, container, false);
        initView();
        new NetMusicTask().execute("http://39.106.204.190:7777/music/search?singer=邓紫棋");
        initListener();
        initRecevier();
        return view;
    }
    //注册广播
    private void initRecevier() {
        mMusicRecevier = new MusicRecevier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.bawei.music.next");
        intentFilter.addAction("com.bawei.music.pre");
        intentFilter.addAction("com.bawei.music.startOrPause");
        getContext().registerReceiver(mMusicRecevier,intentFilter);
    }

    //解除注册
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getContext().unregisterReceiver(mMusicRecevier);
    }

    private void initListener() {
        ivStartOrPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMusicBinder.startOrPause();
            }
        });
        ivNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMusicBinder.next();
                updateMusicUI();
            }
        });
        ivPre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMusicBinder.pre();
                updateMusicUI();
            }
        });
        ivMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popupMenu = new PopupMenu(getContext(),ivMode);
                popupMenu.inflate(R.menu.menu);
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        if(item.getItemId() == R.id.mode_loop){
                            mMusicBinder.setMode(Mode.LOOP);
                        }else if(item.getItemId() == R.id.mode_order){
                            mMusicBinder.setMode(Mode.ORDER);
                        }else if(item.getItemId() == R.id.mode_random){
                            mMusicBinder.setMode(Mode.RANDOM);
                        }
                        return true;
                    }
                });
                popupMenu.show();
            }
        });
        //listView的item点击
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mMusicBinder.playByPosition(position);
                updateMusicUI();
            }
        });
    }

    //必须懒加载：当页面显示的时候再去绑定
    //一定注意！！！！！数据获取成功 再绑定数据
    @Override
    public void onResume() {
        super.onResume();
        initService();
    }

    //绑定服务  记得解绑 稍后
    private void initService() {
        Intent intent = new Intent(getContext(), MusicService.class);
        getContext().startService(intent);
        getContext().bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private void initView() {
        lv = (ListView) view.findViewById(R.id.lv);
        iv = (ImageView) view.findViewById(R.id.iv);
        tvName = (TextView) view.findViewById(R.id.tv_name);
        tvSinger = (TextView) view.findViewById(R.id.tv_singer);
        ivPre = (ImageView) view.findViewById(R.id.iv_pre);
        ivStartOrPause = (ImageView) view.findViewById(R.id.iv_startOrPause);
        ivNext = (ImageView) view.findViewById(R.id.iv_next);
        ivMode = (ImageView) view.findViewById(R.id.iv_mode);
        //获得焦点
        tvName.requestFocus();
        tvSinger.requestFocus();
    }



    //更新下方播放蓝正在播放歌曲的图片和文字
    public void updateMusicUI(){
        String title = mMusicBinder.getCurrentMusic().getTitle();
        String album = mMusicBinder.getCurrentMusic().getAlbum();
        String artist = mMusicBinder.getCurrentMusic().getArtist();
        tvName.setText(title+"");
        tvSinger.setText(artist+"");
        Glide.with(getContext()).load(album).into(iv);
    }

    class NetMusicTask extends AsyncTask<String,Void,String>{
        @Override
        protected String doInBackground(String... strings) {
            return HttpUtils.doGet(strings[0]);
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(getContext(),""+s,Toast.LENGTH_LONG).show();
            //解析数据
            NetSong netSong = new Gson().fromJson(s, NetSong.class);
            mList = netSong.getData();
            mNetSongAdapter = new NetSongAdapter(getContext(),mList);
            lv.setAdapter(mNetSongAdapter);
        }
    }


    //广播接受者：注册广播+接触注册
    class MusicRecevier extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bawei.music.next".equals(intent.getAction())){//避免空指针异常
                mMusicBinder.next();
                updateMusicUI();
            }else  if("com.bawei.music.pre".equals(intent.getAction())){//避免空指针异常
                mMusicBinder.pre();
                updateMusicUI();
            }else if("com.bawei.music.startOrPause".equals(intent.getAction())){//避免空指针异常
                mMusicBinder.startOrPause();
            }
        }
    }
}